<?php


namespace app\services\user;


use app\common\OrderStatus;
use app\models\user\UserModel;
use app\models\user\UserRecordModel;
use think\Model;

class UserRecordService
{
    const PROCESS_TEMPLATE = "修改 %s：%s，改为：%s";

    public static function createRecord($changeUid, $currentUid, $oldInfo, $params)
    {
        $fieldMap = OrderStatus::$arr;
        $changeArr = ['olde_business_id', 'new_business_id', 'status', 'process'];
        $template = self::PROCESS_TEMPLATE;

        foreach ($oldInfo as $key => $value) {
            $oldVal = $value;
            $newVal = $params[$key];
            if ($oldVal == $newVal) {
                continue;
            }
            $fieldName = $fieldMap[$key] ?? '';
            if (!$fieldName) {
                continue;
            }
            if (in_array($key, $changeArr)) {
                if (in_array($key, ['olde_business_id', 'new_business_id'])) {
                    $oldVal = UserModel::where('id', $oldVal)->value('user_name');
                    $newVal = UserModel::where('id', $newVal)->value('user_name');
                }
                if (in_array($key, ['status'])) {
                    $oldVal = OrderStatus::getStatus($oldVal);
                    $newVal = OrderStatus::getStatus($newVal);
                }
                if (in_array($key, ['process'])) {
                    $oldVal = OrderStatus::getProcess($oldVal);
                    $newVal = OrderStatus::getProcess($newVal);
                }
            }
            $context = sprintf($template, $fieldName, $oldVal, $newVal);
            $data = [
                'user_id' => $changeUid,
                'write_user_id' => $currentUid,
                'context' => $context,
            ];
            UserRecordModel::create($data);
        }
    }
}